package com.neu.commons.Utils;

import com.neu.commons.Dao.BaseDao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//可以生成任何表的insert update delete 语句
public class GenerateSqlDao extends BaseDao {
    private String tableName;
    private String pkName;
    private String seqName;

    public GenerateSqlDao(String tableName, String pkName, String seqName) {
        this.tableName = tableName;
        this.pkName = pkName;
        this.seqName = seqName;
    }

    public  final int insert(Map<String,String> item){
        int row=0;
        String sql="insert into "+tableName+"("+pkName+",";
        String values=") values("+seqName+".nextval,";

        List list=new ArrayList();//存放每一个?对应的值
        for(Map.Entry<String,String> entry:item.entrySet()){
            String key=entry.getKey();//获取9的就是列名
            String value=entry.getValue();
            sql+=key+",";
            values+="?,";
            list.add(value);
        }
        sql=sql.substring(0,sql.length()-1);
        values=values.substring(0,values.length()-1);
        sql+=values+")";

        row=super.BaseDaoUpdate(sql,list.toArray());
        return row;
    }
    public final int delete(Map<String,String> item){
        int row=0;
        String sql="delete from "+tableName;
        sql+=" where "+pkName+"=?";
        System.out.println(sql);
        row=super.BaseDaoUpdate(sql,item.get(pkName));
        return row;
    }
    public final int update(Map<String,String> item){
        int row=0;
        String sql="update "+tableName+" set ";
        String set="";
        List param=new ArrayList();
        for (Map.Entry<String,String> entry:item.entrySet()){
            String columnName=entry.getKey();
            String value=entry.getValue();
            set+=","+columnName+"=?";
            param.add(value);
        }
        sql+=set.substring(1);
        sql+=" where "+pkName+"=?";
        param.add(item.get(pkName));
        row=super.BaseDaoUpdate(sql,param.toArray());
        return row;
    }

    public List<Map<String, Object>> findByEqualsParam(Map<String,String>param){
        List<Map<String,Object>>list=null;
        String sql="select * from "+tableName+" where 1=1";
        List p=new ArrayList();
        if (param!=null){
            for ( Map.Entry<String,String>entry:param.entrySet()){
                sql+=" and "+entry.getKey()+"=? ";
                p.add(entry.getValue());
            }
        }

        list=super.BaseDaoQuery(sql,p.toArray());

        return list;


    }

}
